<template>
  <div>
    <div>
      <div class="top-operate">
        <!-- 第一行 -->
        <div>
          <div class="inline-flex">
            <el-select v-model="textCol" class="width-120">
              <el-option label="订单号" value="orderNo"></el-option>
              <el-option label="平台订单号" value="originalNo"></el-option>
              <el-option label="买家姓名" value="customerNickname"></el-option>
              <el-option label="买家手机号" value="customerPhone"></el-option>
            </el-select>
            <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
          </div>
          <div class="inline-flex">
            <el-select v-model="timeCol" class="mar-l-10 width-120">
              <el-option label="创建时间" value="createTime"></el-option>
              <el-option label="发货时间" value="deliveryTime"></el-option>
              <el-option label="收货时间" value="receivedTime"></el-option>
              <el-option label="完成时间" value="completeTime"></el-option>
            </el-select>
            <el-date-picker v-model="timeValue"
              type="daterange"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
          <el-select v-model="orderTypeSearch" placeholder="订单类型" clearable class="mar-l-10 width-140">
            <template v-for="(val, key) in dict.orderType">
              <el-option v-if="key == 35 || key == 36" :key="key" :label="val" :value="key"></el-option>
            </template>
          </el-select>
          <el-button-group class="mar-l-10">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
        <div class="pad-t-10">
          <el-button @click="doExport">导出</el-button>
          <template v-if="!warehouseDeliverFlag">
            <el-button v-if="orderStatus == 1 || orderStatus == 20" @click="doBatchGenerateSend">批量生成发货单</el-button>
          </template>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column width="280px" label="订单信息" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c">
                <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                <div class="font-14 pad-l-10 line-2">
                  <span :title="scope.row.goodsTitle">{{ scope.row.goodsTitle }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="250px" label="订单号">
            <template slot-scope="scope">
              <div>{{scope.row.orderNo}}</div>
              <div v-if="scope.row.externalPlatformType">
                {{ dict.platformType[scope.row.externalPlatformType] }}：{{scope.row.originalNo}}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="订单类型">
            <template slot-scope="scope">
              {{ dict.orderType[scope.row.orderType] }}
            </template>
          </el-table-column>
          <el-table-column width="150px" label="收货人">
            <template slot-scope="scope">
              <div>{{ scope.row.customerNickname }}</div>
              <div class="font-10">{{ scope.row.customerPhone }}</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="商品数量" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.goodsNum}}</div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="订单金额">
            <template slot-scope="scope">
                <div>运费：￥{{ scope.row.freight }}</div>
                <div>商品：￥{{ (scope.row.orderPrice - scope.row.freight).toFixed(2) }}</div>
                <div class="font-blue">合计：￥{{ scope.row.orderPrice }}</div>
            </template>
          </el-table-column>
          <template v-if="distributorRoleFlag">
            <el-table-column width="150px" label="待付金额">
              <template slot-scope="scope">
                  <div>运费：￥{{ scope.row.orderFreightToThird }}</div>
                  <div>商品：￥{{ (scope.row.orderAmountToThird - scope.row.orderFreightToThird).toFixed(2) }}</div>
                  <div class="font-blue">合计：￥{{ scope.row.orderAmountToThird }}</div>
              </template>
            </el-table-column>
          </template>
          <el-table-column width="200px" label="时间" align="center">
            <template slot-scope="scope">
              <div>创建：{{ scope.row.createTime }}</div>
              <div v-if="scope.row.deliveryTime">发货：{{ scope.row.deliveryTime }}</div>
              <div v-if="scope.row.receivedTime">收货：{{ scope.row.receivedTime }}</div>
              <div v-if="scope.row.completeTime">完成：{{ scope.row.completeTime }}</div>
              <div v-if="scope.row.cancelTime">取消：{{ scope.row.cancelTime }}</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="包裹数量" prop="packageNum" align="center">
          </el-table-column>
          <el-table-column width="100px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.orderStatus == 1" type="text" size="medium" class="table-btn" @click="doCancel(scope.row)">取消订单</el-button>
              <el-button type="text" size="medium" class="table-btn" @click="doLinkDetail(scope.row)">查看详情</el-button>
              <template v-if="!warehouseDeliverFlag">
                <el-button type="text" size="medium" v-if="scope.row.enterpriseDeliveryFlag == 1" class="table-btn" @click="doOpenDeliver(scope.row)">发货</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 发货单管理dialog -->
    <el-dialog width="1200px" v-el-drag-dialog title="发货单管理" :visible.sync="orderDeliverVisible" :show-close="false">
      <order-send-manage :showFlag="orderDeliverVisible" 
        :apartOrderId="selectApartOrderId" 
        @callback="doCallbackOrderDeliver">
      </order-send-manage>
    </el-dialog>

  </div>
</template>

<script>
  import { pageProjectOrder, doCancelOrder } from '@/api/goods/order'
  import { getDictByGroupName, downloadFile } from '@/api/common/common'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import orderSendManage from '@/views/goods/order/components/order-send-manage'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    components: { orderSendManage },
    directives: {
      elDragDialog
    },
    props: {
      orderStatus: {
        type: String,
        default: 0
      }
    },
    watch: {
      orderStatus() {
        this.searchListQuery.currentPage = 1
        this.initList()
      }
    },
    data() {
      return {
        // 文本model
        textCol: 'orderNo',
        textValue: '',
        // 时间model
        timeCol: 'createTime',
        timeValue: [],
        // 订单类型
        orderTypeSearch: '',
        // 默认查询条件
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          orderTypes: '35,36'
        },
        // 查询条件
        searchListQuery: {},
        // 数据字典
        dict: {
          platformType: {},
          orderType: {}
        },
        // 分销商角色flag
        distributorRoleFlag: false,
        // 发货订单id
        selectApartOrderId: '',
        // 仓库发货flag
        warehouseDeliverFlag: false,
        orderDeliverVisible: false,
        total: 0,
        listLoading: false,
        dataList: [],
        multipleSelection: []
      }
    },
    // 初始化页面
    created() {
      this.distributorRoleFlag = this.getSystemRoleType() === '4'
      Object.assign(this.searchListQuery, this.defaultQuery)
      // 获取数据字典
      getDictByGroupName('ThirdOrderDTO.platformType').then(response => {
        Object.assign(this.dict, response.data)
      })
      // 获取企业配置
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        this.enterpriseConfig = response.data
        this.warehouseDeliverFlag = this.enterpriseConfig.warehouseAuthority === 1 && this.enterpriseConfig.warehouseDeliverFlag === 1
      })
      this.initList()
    },
    methods: {
      // tab切换事件
      doChangeTab() {
        this.initList()
      },
      // 初始化
      initList() {
        this.listLoading = true
        this.setSearchListQuery()
        pageProjectOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          Object.assign(this.dict, response.data.dict)
        })
      },
      // 设置查询条件
      setSearchListQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.timeCol
        this.searchListQuery.startDate = (this.timeValue && this.timeValue.length > 0) ? this.timeValue[0] : ''
        this.searchListQuery.endDate = (this.timeValue && this.timeValue.length > 1) ? this.timeValue[1] : ''
        this.searchListQuery.orderStatus = this.orderStatus
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        if (this.distributorRoleFlag) {
          this.searchListQuery.memberId = this.getMemberId()
        } else {
          this.searchListQuery.memberIdIsNull = 1
        }
        if (this.orderTypeSearch) {
          this.searchListQuery.orderTypes = []
          this.searchListQuery.orderType = this.orderTypeSearch
        }
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.timeCol = originData.timeCol
        this.timeValue = originData.timeValue
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 跳转详情事件
      doLinkDetail(row) {
        // this.$router.push({ path: '/order/order/detail/index', query: { orderId: row.orderId }})
        const routeData = this.$router.resolve({
          path: '/order/order/detail/index',
          query: { orderId: row.orderId }
        })
        window.open(routeData.href, '_blank')
      },
      // 取消事件
      doCancel(row) {
        this.$confirm('确定取消订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          doCancelOrder({ orderId: row.orderId }).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.initList()
            this.$message({ message: '取消成功', type: 'success' })
          })
        }).catch(() => {
        })
      },
      // 导出事件
      doExport() {
        const url = '/goods/projectOrder/exportOrder'
        if (this.multipleSelection.length > 0) {
          const orderIds = this.multipleSelection.map(item => item.orderId)
          downloadFile(url, { enterpriseId: this.getEnterpriseId(), orderIds: orderIds.join(',') }, '订单.xlsx')
        } else {
          if (this.dataList.length === 0) {
            this.$message({ message: '暂无可导出数据', type: 'warning' })
            return
          }
          this.setSearchListQuery()
          downloadFile(url, this.searchListQuery, '订单.xlsx')
        }
      },
      // 批量生成发货单事件
      doBatchGenerateSend() {
        if (this.multipleSelection.length <= 0) {
          this.$message({ message: '请勾选数据', type: 'warning' })
          return
        }
        const params = {
          enterpriseId: this.getEnterpriseId(),
          systemRoleType: this.getSystemRoleType(),
          orderIds: this.multipleSelection.map(item => item.orderId)
        }
        this.$bus.$emit('asyncHandle', '300003', params, () => {
          this.initList()
        })
      },
      // 打开发货dialog事件
      doOpenDeliver(row) {
        this.selectApartOrderId = row.apartOrderId
        this.orderDeliverVisible = true
      },
      // 订单发货回调事件
      doCallbackOrderDeliver(callbackFlag) {
        if (callbackFlag) {
          this.$emit('refreshStat')
          this.initList()
        }
        this.orderDeliverVisible = false
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .table-btn {
    padding: 5px 0px !important;
  }
</style>
